<template>
  <div class="signed-agreenment-view view-container">

    <div class="main-content">
      <div class="list-container">

        <div
            class="filter-container"
            style="padding: 0"
        >

          <el-form
              :inline="true"
              :model="formData"
              class="filter-form-inline"
              label-position="right"
              label-width="80px"
              size="small"
          >

            <el-row
                :gutter="20"
                style="margin-left: 0px; margin-right: 0px"
            >
              <el-col :span="5">
                <el-form-item
                    label="状态"
                    style="width: 100%"
                >
                  <el-select
                      v-model="formData.agentProductStatus"
                      clearable
                      placeholder="请选择状态"
                      style="width: 100%"
                      @change="listSearch"
                  >
                    <el-option
                        v-for="item in statusOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="5">
                <el-form-item
                    label="代理类型"
                    style="width: 100%"
                >
                  <el-select
                      v-model="formData.agentType"
                      clearable
                      placeholder="请选择代理类型"
                      style="width: 100%"
                      @change="listSearch"
                  >
                    <el-option label="企业代理" value="agent"></el-option>
                    <el-option label="兼职大包" value="agent_person"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="5">
                <el-form-item
                    label="代理名称"
                    style="width: 100%"
                >
                  <el-input v-model="formData.keyWord" clearable placeholder="请输入代理名称"/>
                </el-form-item>
              </el-col>

              <el-col
                  :span="4"
              >
                <el-form-item style="width: 100%">
                  <more-search-btn v-model:is-more="visible" style="margin-left: 10px"/>
                </el-form-item>
              </el-col>

              <el-col :span="5">
                <el-form-item style="width: 100%">
                  <el-button
                      class="border-btn"
                      @click="reset"
                  >重置
                  </el-button>
                  <el-button
                      class="main-btn"
                      type="primary"
                      @click="listSearch"
                  >搜索
                  </el-button>
                </el-form-item>
              </el-col>

              <template v-if="visible">

                <el-col :span="5">
                  <el-form-item label="产品信息" style="width: 100%">
                    <el-select
                        v-model="formData.productId"
                        :loading="loading"
                        :remote-method="remoteMethod"
                        clearable
                        filterable
                        placeholder="请选择产品"
                        remote
                        reserve-keyword
                        @change="listSearch"
                    >
                      <el-option
                          v-for="item in products"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                      />
                    </el-select>

                  </el-form-item>
                </el-col>

                <el-col :span="5">
                  <el-form-item label="负责职员" style="width: 100%">
                    <el-select
                        v-model="formData.headId"
                        clearable
                        placeholder="请选择职员"
                        style="width: 100%"
                        @change="listSearch"
                    >
                      <el-option
                          v-for="item in headOptions"
                          :key="item.id"
                          :label="item.realName"
                          :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="5">
                  <el-form-item label="代理地区" style="width: 100%">
                    <el-cascader
                        v-model="formData.area"
                        :options="citys"
                        :props="{ checkStrictly : true, expandTrigger: 'hover', label: 'regionName', value:'regionCode' }"
                        :show-all-levels="false"
                        clearable
                        placeholder="请选择代理地区"
                        style="width: 100%;"
                        @change="areaChange"
                    />
                  </el-form-item>

                </el-col>

              </template>

              <el-col v-auth="{v:['crm:cooperation:signed:pms']}" :span="24">
                <el-button class="main-btn" size="small" style="margin-bottom: 20px" type="primary" @click="addClick">
                  新建区域招商要素
                </el-button>
              </el-col>

            </el-row>
          </el-form>

        </div>

        <table-view
            :data="tableData"
            :visible="visible"
            @row-click="rowClick"
        >
          <el-table-column
              align="center"
              fixed="left"
              label="编号"
              prop="agentProductNumber"
              show-overflow-tooltip
              width="100"
          />
          <el-table-column
              align="left"
              fixed="left"
              header-align="center"
              label="代理名称"
              prop="agentName"
              show-overflow-tooltip
              width="150"
          >
            <template #default="{row}">
              <span v-if="row.agentType == 'agent'">{{ row.agentName }}</span>
              <span v-else>{{ row.userName }}</span>
            </template>
          </el-table-column>
          <el-table-column
              align="left"
              fixed="left"
              header-align="center"
              label="通用名"
              prop="productPopularName"
              show-overflow-tooltip
              width="150"
          />
          <el-table-column
              align="center"
              label="商品名"
              prop="productName"
              show-overflow-tooltip
              width="100"
          />
          <el-table-column
              align="center"
              label="包装规格"
              prop="packSpecs"
              show-overflow-tooltip
              width="100"
          />
          <el-table-column
              align="center"
              label="生产厂家"
              prop="producer"
              show-overflow-tooltip
              width="100"
          />
          <!-- <el-table-column
              align="center"
              label="可营销终端"
              width="150"
          >
            <template #default="{row}">
              {{ getLabel('app_mode', row.terminalType) }}
            </template>
          </el-table-column> -->
          <el-table-column
              align="center"
              label="代理地区"
              width="200"
          >
            <template #default="{row}">
              <area-list-view :areas="row.region"/>
            </template>
          </el-table-column>
          <el-table-column
              align="center"
              label="交易价(元)"
              width="150"
          >
            <template #default="{row}">
              <div class="tab-line">
                <div>{{ row.tradePrice }}</div>
                <div
                        v-if="row.flowStatus == 'DOING' && (row.processDefinitionKey == 'agentProductChangePrice' || row.processDefinitionKey == 'agentPersonProductChangePrice')"
                        class="flow-status-color"
                >[交易价变更审核中]
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
              align="center"
              label="代理期限至"
              width="100"
          >
            <template #default="{row}">
              {{ dateFormat('yyyy-mm-dd', row.agentEndTime) }}
            </template>
          </el-table-column>
          <el-table-column
              align="center"
              label="负责营销职员"
              prop="headName"
              width="150"
          />
          <el-table-column
              align="center"
              label="创建时间"
              width="150"
          >
            <template #default="{row}">
              {{ dateFormat('yyyy-mm-dd HH:MM', row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column
              align="center"
              fixed="right"
              label="状态"
              min-width="150px"
          >
            <template #default="{row}">
              <div class="tab-line">
                <!--                                <template v-if="(row.processDefinitionKey == 'agentProductCreate' || row.processDefinitionKey == 'agentPersonProductCreate')-->
                <!--                        && (row.flowStatus=='DOING' || row.flowStatus=='REFUSE' || row.flowStatus=='REPEAL')">-->
                <!--                                    <span>{{ getLabel('approval_result',row.flowStatus) }}</span>-->
                <!--                                </template>-->
                <div v-if="row.flowStatus==='REPEAL' && row.processDefinitionKey == 'agentProductCreate'">{{ getLabel('approval_result', row.flowStatus) }}</div>
                <div v-else>{{ getLabel('agreement_status', row.agentProductStatus) }}</div>
                <template v-if="row.flowStatus=='DOING'">
                  <div
                      v-if="row.processDefinitionKey == 'agentProductBan'"
                      class="flow-status-color"
                  >[作废审核中]
                  </div>
                  <div
                      v-else-if="row.processDefinitionKey !== 'agentProductCreate' && row.processDefinitionKey !== 'agentPersonProductCreate'"
                      class="flow-status-color"
                  >[{{ getLabel('approval_result', row.flowStatus) }}]
                  </div>
                </template>
                <div
                    v-else-if="row.flowStatus==='REJECT_INITIATOR'"
                    class="flow-status-color"
                >[ {{ getLabel('approval_result', row.flowStatus) }} ]
                </div>
               
              </div>
            </template>
          </el-table-column>
          <el-table-column
              align="center"
              fixed="right"
              label="操作"
              min-width="100px"
          >
            <template #default="{row}">
              <!--              <el-button-->
              <!--                v-if="row.agentProductStatus == 2"-->
              <!--                type="text"-->
              <!--                @click="onTerminal(row)"-->
              <!--              >添加配送终端</el-button>-->
              <el-button
                  v-auth="{v:['crm:cooperation:signed:pms'],bool:row.agentProductStatus == -1 || row.agentProductStatus == -2 || row.flowStatus==='REJECT_INITIATOR' || row.flowStatus==='REPEAL'}"
                  class="delete-text-btn"
                  type="text"
                  @click="onDelete(row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </table-view>

        <Pagination
            v-model:limit="formData.pageSize"
            v-model:page="formData.page"
            :total="total"
            style="display: flex; justify-content: flex-end"
            @pagination="getList"
        />

      </div>
    </div>

    <addAgreementDialog
        ref="refDialog"
        @success="getList"
    />

    <!--    <terAndDisDialog-->
    <!--      ref="terAndDisDialog"-->
    <!--      @success="getList"-->
    <!--    />-->
  </div>
</template>

<script>
import {crmStore} from "../../../../../store";
import {getProductName} from "../../../../../../../utils/commonFun";
import area from "../../../../../../../utils/area";
import {useRouter} from 'vue-router'
import {defineAsyncComponent, defineComponent, getCurrentInstance, inject, onMounted, reactive, toRefs,} from 'vue'

export default defineComponent({
  name: 'marketingSignedAgreement',
  components: {
    addAgreementDialog: defineAsyncComponent(() =>
        import('../../../modules/addAgreementDialog.vue')
    ),
    // terAndDisDialog: defineAsyncComponent(() =>
    //         import('../../../modules/terAndDisDialog.vue')
    // )
  },
  setup() {
    const router = useRouter()
    const currentInstance = getCurrentInstance()
    const api = inject('api')
    const statusOptions = crmStore.getters['dictionary/getDictionary']['agreement_status']
    const headOptions = crmStore.getters['company/getHeadOptions']
    const citys = area
    var data = reactive({
      activeName: '1',
      formData: {
        page: 1,
        pageSize: 20,
        productId: '',
        headId: '',
        agentProductStatus: '',
        keyWord: '',
        area: [],
        agentAttribute: '1',
        tabStatus: '1',
      },
      tableData: [],
      total: 0,
      visible: false,
      refDialog: null,
      terAndDisDialog: null,
      loading: false,
      products: [],
      searchStr: ''
    })

    const handleClick = () => {
      data.tableData = []
      data.formData.page = 1
      getList()
    }

    const addClick = () => {
      data.refDialog.open(1)
    }

    const reset = () => {
      data.formData = {
        page: 1,
        pageSize: 20,
        productId: '',
        headId: '',
        agentProductStatus: '',
        keyWord: '',
        area: [],
        agentAttribute: '1',
        tabStatus: '1',
      }

      getList()
    }

    const listSearch = () => {
      data.tableData = []
      data.formData.page = 1
      getList()
    }

    const rowClick = (row, column) => {
      if (column.label === '操作') return
      router.push({name: 'signedAgreementDetail', query: {id: row.id}})
    }

    const onTerminal = (row) => {
      data.terAndDisDialog.open(row)
    }

    const areaChange = () => {
      listSearch()
    }

    const remoteMethod = (query) => {
      data.products = []
      data.loading = true
      data.searchStr = query

      if (query) {
        const pam = {
          keyWord: query,
        }
        api.common.GET_PRODUCT_LIST(pam).then((res) => {
          if (!res.code && res.data) {
            // if (query == data.searchStr) {
            //
            // }
            res.data.list.forEach(a => {
              a.name = getProductName(a)
            })
            data.products = res.data.list

          } else {
            currentInstance.proxy.customMessage({type: 'error', message: res.msg})
          }
          data.loading = false
        })
      } else {
        data.loading = false
      }
    }

    const getList = () => {
      let a = {...data.formData}
      a.headId = Number(a.headId)
      a.productId = Number(a.productId)
      if (a.area.length) {
        if (a.area.length == 1) {
          a.provinceCode = a.area[0]
        } else if (a.area.length == 2) {
          a.cityCode = a.area[1]
        } else if (a.area.length == 3) {
          a.areaCode = a.area[2]
        }
      }
      api.signedAgent.AGENT_PRODUCT_LIST(a).then((res) => {
        if (!res.code && res.data) {
          data.tableData = res.data.list
          data.total = res.data.total
        } else {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: res.msg,
          })
        }
      })
    }

    const getStatus = (row) => {
      switch (row.agentProductStatus) {
        case '-2':
          return '已作废'
        case '-1':
          return '未通过'
        case '1':
          return '审核中'
        case '2':
          return '有效'
      }
    }

    const onDelete = (row) => {
      currentInstance.proxy
          .alertBox({
            message: '删除数据后不可恢复，确认删除？',
            title: '删除',
          })
          .then(() => {
            api.signedAgent.AGENT_PRODUCT_DELETE(row.id).then((res) => {
              if (res.code) {
                currentInstance.proxy.customMessage({
                  type: 'error',
                  message: res.msg,
                })
              } else {
                currentInstance.proxy.customMessage({
                  type: 'success',
                  message: '删除成功',
                })
                getList()
              }
            })
          })
          .catch((err) => {
            console.log(err)
          })
    }

    onMounted(() => {
      getList()
    })

    return {
      ...toRefs(data),
      statusOptions,
      headOptions,
      citys,

      handleClick,
      addClick,
      listSearch,
      getList,
      reset,
      rowClick,
      getStatus,
      onTerminal,
      onDelete,
      areaChange,
      remoteMethod,
    }
  },
})
</script>

<style scoped>
</style>
